export const compass = (base64, targSize = 512 * 512, quality = 0.9) => {
    return new Promise((resolve) => {
        if (base64.length <= targSize) {
            resolve(base64);
            return;
        }
        const newImage = new Image();
        newImage.src = base64;
        console.log(base64.length, targSize)
        newImage.setAttribute("crossOrigin", 'Anonymous'); //url为外域时需要
        newImage.onload = function () {
            //let quality = 0.6; //压缩系数0-1之间
            const canvas = document.createElement("canvas");
            const ctx = canvas.getContext("2d");
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
            let base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
            // 如想确保图片压缩到自己想要的尺寸,如要求在5-10kb之间，请加以下语句，quality初始值根据情况自定
            // console.log(base64.length + "循环1压缩" + (base64.length / 1024 > 512))

            while (base64.length > targSize) {
                quality -= 0.05;
                // console.log(base64.length + "循环压缩" + quality)
                base64 = canvas.toDataURL("image/jpeg", quality);
            }
            resolve(base64)
        }
    })
}

// export const compass = (base64, targSize = 512 * 512, callback) => {
//     if (base64.length <= targSize) {
//         callback(base64);
//         return
//     }
//     const newImage = new Image();
//     newImage.src = base64;
//     console.log(base64.length, targSize)
//     newImage.setAttribute("crossOrigin", 'Anonymous'); //url为外域时需要
//     newImage.onload = function () {
//         let quality = 0.6; //压缩系数0-1之间
//         const canvas = document.createElement("canvas");
//         const ctx = canvas.getContext("2d");
//         ctx.clearRect(0, 0, canvas.width, canvas.height);
//         ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
//         let base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
//         // 如想确保图片压缩到自己想要的尺寸,如要求在5-10kb之间，请加以下语句，quality初始值根据情况自定
//         // console.log(base64.length + "循环1压缩" + (base64.length / 1024 > 512))
//
//         while (base64.length > targSize) {
//             quality -= 0.05;
//             // console.log(base64.length + "循环压缩" + quality)
//             base64 = canvas.toDataURL("image/jpeg", quality);
//         }
//         callback(base64); //必须通过回调函数返回，否则无法及时拿到该值
//     }
// }